package com.dabai.wifiseepass.activitys;

import android.Manifest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dabai.wifiseepass.R;
import com.dabai.wifiseepass.bean.BaseNetObject;
import com.dabai.wifiseepass.utils.Base64;
import com.dabai.wifiseepass.utils.DabaiUtils;
import com.dabai.wifiseepass.utils.DateUtils;
import com.dabai.wifiseepass.utils.WifiAdmin;
import com.dabai.wifiseepass.utils.WifiInfo;
import com.dabai.wifiseepass.utils.WifiManage;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.tencent.bugly.beta.Beta;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case android.R.id.home:
                // 处理返回逻辑
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        private Context context;
        private String TAG = "dabaizzz";
        private WifiAdmin wifiAdmin;

        private int checkResult;


        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            context = getContext();
            //version init  版本号初始化
            final Preference ver = getPreferenceManager().findPreference("other_version");

            //change preference version name;
            ver.setSummary(new DabaiUtils().getVersionName(context));
            wifiAdmin = new WifiAdmin(context);

        }

        /**
         * 删除所有WiFi密码
         *
         * @return
         */

        public void delallWIFI() {

            //删除所有WiFi
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiManage.removeAllWifi(context, wifiManager);

        }


        @Override
        public boolean onPreferenceTreeClick(Preference preference) {

            switch (preference.getKey()) {
                case "other_delall":

                    if (!jianchadingwei()) {
                        break;
                    }

                    AlertDialog drop = new AlertDialog.Builder(context)
                            .setTitle("警告")
                            .setMessage("此操作会取消保存所有WiFi信息，删除所有已保存的WiFi密码！")
                            .setPositiveButton("开始验证", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    //P以下
                                    KeyguardManager km = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);

                                    if (km.isKeyguardSecure()) {
                                        Intent kmr = km.createConfirmDeviceCredentialIntent("警告", "这个设备的主人是你嘛?");
                                        startActivityForResult(kmr, 888);

                                    } else {

                                        delallWIFI();

                                        Toast to = Toast.makeText(context, "没有设置屏幕锁，跳过验证", Toast.LENGTH_SHORT);
                                        to.setGravity(Gravity.CENTER, 0, 0);
                                        to.show();
                                    }
                                }
                            })
                            .show();

                    break;
                case "other_feedback":

                    new DabaiUtils().openLink(context, "https://support.qq.com/products/134723/faqs-more/");

                    break;
                case "other_version":
                    Beta.checkUpgrade();
                    //new DabaiUtils().openLink(context, "https://www.coolapk.com/apk/com.dabai.wifiseepass");
                    break;
                case "other_create":

                    startActivity(new Intent(context, CreateActivity.class));

                    break;

                case "other_share":
                    new DabaiUtils().shareFromCoolapk(context);
                    break;

                case "other_backup":

                    new MaterialDialog.Builder(context)
                            .items(R.array.backup)
                            .itemsCallback((dialog, view, which, text) -> {
                                switch (text + "") {
                                    case "网络备份":
                                        if (!jiancha()) {
                                            return;
                                        }

                                        AlertDialog alertDialog = DabaiUtils.showDialog(context, "正在备份...");

                                        BaseNetObject baseNetObject = new BaseNetObject();
                                        baseNetObject.setPhoneName(DabaiUtils.getDeviceName(context));
                                        baseNetObject.setPhoneId(DabaiUtils.getDeviceID(context));

                                        List<WifiInfo> wifiInfo;
                                        try {
                                            wifiInfo = WifiManage.Read();
                                        } catch (Exception e) {
                                            alertDialog.setMessage("备份失败," + e.getMessage());
                                            return;
                                        }
                                        String jsonString1 = JSON.toJSONString(wifiInfo);
                                        String wifiBase = Base64.encode(jsonString1);

                                        baseNetObject.setContent(wifiBase);

                                        baseNetObject.save(new SaveListener<String>() {
                                            @Override
                                            public void done(String s, BmobException e) {

                                                if (e == null) {
                                                    alertDialog.dismiss();
                                                    new MaterialAlertDialogBuilder(context)
                                                            .setTitle("提示")
                                                            .setCancelable(false)
                                                            .setMessage("备份完成,你的网络恢复码为:" + baseNetObject.getObjectId())
                                                            .setNeutralButton("取消",null)
                                                            .setPositiveButton("复制", (dialog12, which12) -> DabaiUtils.copyText(context, baseNetObject.getObjectId())).show();
                                                } else {
                                                    alertDialog.setMessage("备份失败," + e.getMessage());
                                                }
                                            }
                                        });

                                        return;
                                    case "网络恢复":

                                        if (!jianchadingwei()) {
                                            return;
                                        }

                                        new MaterialDialog.Builder(context)
                                                .title("使用网络恢复码")
                                                // .content("")
                                                .inputType(InputType.TYPE_CLASS_TEXT)
                                                .cancelable(false)
                                                .input("请输入网络恢复码", null, (dialog13, input) -> {

                                                    if (input.length()<8){
                                                        DabaiUtils.showDialog(context, "恢复异常!");
                                                    }else {

                                                        //查找BaseNetObject表里面id为6b6c11c537的数据
                                                        BmobQuery<BaseNetObject> bmobQuery = new BmobQuery<>();
                                                        bmobQuery.getObject("" + input, new QueryListener<BaseNetObject>() {
                                                            @Override
                                                            public void done(BaseNetObject object, BmobException e) {
                                                                if (e == null) {

                                                                    new MaterialAlertDialogBuilder(context)
                                                                            .setTitle("恢复信息确认")
                                                                            .setMessage("备份设备识别码:" + object.getPhoneName() + "\n备份日期:" + object.getCreatedAt())
                                                                            .setPositiveButton("确定", (dialog14, which13) -> {
                                                                                String wifisjson = Base64.decode(object.getContent());
                                                                                huifuWifis(wifisjson);
                                                                            }).setNeutralButton("取消", null)
                                                                            .show();

                                                                } else {
                                                                    DabaiUtils.showDialog(context, "恢复异常!");
                                                                }
                                                            }
                                                        });
                                                    }

                                                })
                                                .neutralText("取消")
                                                .positiveText("确定")
                                                .show();



                                        return;
                                    case "导出文件":

                                        if (!jiancha()) {
                                            return;
                                        }

                                        /**
                                         * SAF框架写入文件
                                         */
                                        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
                                        // 只显示可以打开的文件
                                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                                        intent.setType("application/json");
                                        intent.putExtra(Intent.EXTRA_TITLE, "WiFi配置备份_" + DateUtils.getTime(3) + ".json");

                                        startActivityForResult(intent, 101);
                                        return;
                                    case "导入文件":

                                        if (!jianchadingwei()) {
                                            return;
                                        }


                                        //通过系统的文件浏览器选择一个文件
                                        Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                                        //筛选，只显示可以“打开”的结果，如文件(而不是联系人或时区列表)
                                        intent2.addCategory(Intent.CATEGORY_OPENABLE);
                                        //过滤只显示图像类型文件
                                        intent2.setType("*/*");
                                        startActivityForResult(intent2, 102);
                                        return;
                                    case "显示全部WiFi配置码":

                                        if (!jiancha()) {
                                            return;
                                        }

                                        List<WifiInfo> wifiInfos = null;
                                        try {
                                            wifiInfos = WifiManage.Read();
                                        } catch (Exception e) {
                                            Toast.makeText(context, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        String jsonString = JSON.toJSONString(wifiInfos);

                                        final String wifisbase = Base64.encode(jsonString);

                                        new MaterialAlertDialogBuilder(context)
                                                .setTitle("全部WiFi配置码").setMessage("" + wifisbase)
                                                .setPositiveButton("复制", (dialog1, which1) -> DabaiUtils.copyText(context, wifisbase)).show();

                                        return;
                                    case "使用配置码":

                                        if (!jianchadingwei()) {
                                            return;
                                        }

                                        /**
                                         * 使用配置码
                                         */

                                        usePeizhima();

                                        return;
                                }

                            })
                            .show();

                    break;

            }
            return super.onPreferenceTreeClick(preference);
        }


        /**
         * 使用配置码 转 WiFi信息数组，恢复WiFi配置
         */
        private void usePeizhima() {

            new MaterialDialog.Builder(context)
                    .title("使用配置码")
                    // .content("")
                    .inputType(InputType.TYPE_CLASS_TEXT)
                    .cancelable(false)
                    .input("请输入WiFi配置码", null, (dialog, input) -> {

                        String wifisbase = input + "";

                        if (wifisbase.isEmpty()){
                            DabaiUtils.showDialog(context, "恢复异常!");
                            return;
                        }

                        Base64 base = new Base64();
                        String wifisjson = base.decode(wifisbase);

                        huifuWifis(wifisjson);

                    })
                    .neutralText("取消")
                    .positiveText("确定")
                    .show();

        }

        //检查定位权限
        private boolean jianchadingwei() {
            checkResult = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            //if(!=允许),抛出异常
            if (checkResult != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); // 动态申请读取权限
                Toast.makeText(context, "缺少必要的定位权限！", Toast.LENGTH_SHORT).show();
                return false;
            }
            return true;
        }

        //检查root和存在的WiFi信息数量
        private boolean jiancha() {

            if (!DabaiUtils.isRoot()) {
                Toast.makeText(context, "没有WiFi信息可以导出！", Toast.LENGTH_SHORT).show();
                return false;
            }

            try {
                List<WifiInfo> wifiInfos = WifiManage.Read();
                if (wifiInfos.size() <= 0) {
                    Toast.makeText(context, "没有WiFi信息可以导出！", Toast.LENGTH_SHORT).show();
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;

        }


        //回调SAF的Uri
        @Override
        public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);


            //指纹验证结果
            if (resultCode == RESULT_OK && requestCode == 888) {
                delallWIFI();
            } else if (resultCode == RESULT_CANCELED && requestCode == 888) {
                Toast.makeText(context, "验证身份失败!", Toast.LENGTH_SHORT).show();
            }

            Uri uri = null;

            if (resultCode == Activity.RESULT_OK) {

                if (requestCode == 101) {

                    if (data != null) {
                        uri = data.getData();
                    }
                    if (uri != null) {
                        try {
                            List<WifiInfo> wifiInfos = WifiManage.Read();
                            String jsonString = JSON.toJSONString(wifiInfos);

                            //写入文本
                            boolean isok = writeDocument(uri, jsonString);

                            if (isok) {
                                Toast.makeText(context, "导出成功:" + new DabaiUtils().UritoPath(context, uri), Toast.LENGTH_LONG).show();
                            }

                        } catch (Exception e) {
                            Toast.makeText(context, "导出失败!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }


                if (requestCode == 102) {

                    if (data != null) {
                        uri = data.getData();
                    }
                    if (uri != null) {
                        try {

                            String json = readDocument(uri);
                            huifuWifis(json);

                        } catch (Exception e) {
                            Toast.makeText(context, "导入失败!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }

        //通过URI写入文本的方法
        private boolean writeDocument(Uri uri, String text) {
            boolean a = false;
            if (uri != null) {
                OutputStream outputStream = null;
                try {
                    // 获取 OutputStream
                    outputStream = context.getContentResolver().openOutputStream(uri);
                    outputStream.write(text.getBytes(StandardCharsets.UTF_8));
                    a = true;
                } catch (IOException e) {
                    a = false;
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.fillInStackTrace();
                        }
                    }
                }
            }
            return a;
        }

        //通过URI读取文本的方法
        private String readDocument(Uri uri) {
            StringBuffer sb1 = new StringBuffer();
            if (uri != null) {
                InputStream inputStream = null;
                try {
                    // 获取 OutputStream
                    inputStream = context.getContentResolver().openInputStream(uri);

                    int byteCount = 0;
                    byte[] bytes = new byte[1024];

                    while ((byteCount = inputStream.read(bytes)) != -1) {
                        sb1.append(new String(bytes, 0, byteCount));
                    }

                } catch (IOException e) {

                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.fillInStackTrace();
                        }
                    }
                }
            }
            return sb1.toString();
        }


        /**
         * 恢复 WiFi配置
         *
         * @param s
         */
        ProgressDialog pd1;

        private void huifuWifis(String s) {

            try {
                final JSONArray jsonArray = JSONArray.parseArray(s);

                new MaterialDialog.Builder(context)
                        .title("即将恢复的WiFi")
                        .content(readWifiList(jsonArray))
                        .positiveText("确认")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                pd1 = new ProgressDialog(context);
                                pd1.setTitle("恢复进度");
                                pd1.setIndeterminate(false);
                                pd1.setMax(jsonArray.size());
                                pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                pd1.show();

                                new Thread() {
                                    @Override
                                    public void run() {
                                        super.run();
                                        //新线程操作
                                        for (int i = 0; i < jsonArray.size(); i++) {

                                            JSONObject jo = (JSONObject) jsonArray.get(i);
                                            String ssid = jo.getString("ssid");
                                            String pass = jo.getString("password");

                                            if (pass.equals("无密码")) {
                                                wifiAdmin.addNetwork(ssid, pass, WifiAdmin.TYPE_NO_PASSWD);
                                            } else {
                                                wifiAdmin.addNetwork(ssid, pass, WifiAdmin.TYPE_WPA);

                                            }

                                            pd1.setProgress(i + 1);

                                        }

                                        pd1.dismiss();

                                    }
                                }.start();
                            }
                        })
                        .negativeText("取消")
                        .show();


            } catch (Exception e) {
                Toast.makeText(context, "恢复文件异常！", Toast.LENGTH_SHORT).show();
            }
        }

        public String readWifiList(JSONArray jsonArray) {

            StringBuffer sb2 = new StringBuffer();
            try {

                for (Object ob : jsonArray) {
                    JSONObject jo = (JSONObject) ob;
                    String ssid = jo.getString("ssid");
                    String pass = jo.getString("password");

                    sb2.append("名称:" + ssid + "\n" + "密码:" + pass + "\n\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sb2.toString();
        }


    }


}